package tailLogManager

import (
	"code.oldboy.com/studygo/LogAgent/etcd"
	"code.oldboy.com/studygo/LogAgent/tailLog"
	"fmt"
)

var tailManager *tailLogManager

type tailLogManager struct {
	LogEntry []*etcd.LogEntry
	taskMap map[string]*tailLog.TailTask
	newConfChan chan []*etcd.LogEntry
}

func Init(logEntry []*etcd.LogEntry)  {
	tailManager=&tailLogManager{
		LogEntry: logEntry,
		taskMap: make(map[string]*tailLog.TailTask,32),
		newConfChan: make(chan []*etcd.LogEntry),
	}
	for _,r:=range  tailManager.LogEntry{
		tailTask := tailLog.NewTailTask(r.Path, r.Topic)
		tailManager.taskMap[getKey(r.Path,r.Topic)]=tailTask
	}

	go tailManager.run()

}

func getKey(path ,topic string)(key string){
	return path+"_"+topic
}
//监听通道 更新配置信息
func (tskMgr *tailLogManager) run(){
	var newConf  []*etcd.LogEntry
	fmt.Printf("run newConf:= %v",newConf)
	for newConf=range  tskMgr.newConfChan{
		for _,task:= range newConf{
			_,ok := tskMgr.taskMap[getKey(task.Path,task.Topic)]
			if ok {
				continue
			}else {
				TailObj := tailLog.NewTailTask(task.Path, task.Topic)
				tskMgr.taskMap[getKey(task.Path,task.Topic)]=TailObj
			}
		}

		fmt.Printf("新配置来了:= %v",newConf)
		for _,c1:=range tskMgr.LogEntry{
			isDelete:=true
			for _,c2:=range newConf{
				if  c1.Path==c2.Path&&c1.Topic==c2.Topic {
					isDelete=false
					break
				}
			}
			if isDelete {
				task := tskMgr.taskMap[getKey(c1.Path, c1.Topic)]
				task.Done()
			}
		}
	}
}
func GetNewConfChan()(c chan []*etcd.LogEntry){
	return  tailManager.newConfChan
}

